package sichuan.ytf.thread;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建一个固定大小的线程池
//        ExecutorService service = Executors.newFixedThreadPool(3);
        ExecutorService service = new ThreadPoolExecutor(50, 50, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(500));

        for (int i = 0; i < 10; i++) {
            System.out.println("创建线程" + i);
            int j = i;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try {
                        if (j == 1)
                            Thread.sleep(2000);
                        System.out.println("执行线程" + j);
                    } catch (InterruptedException e) {
                        System.out.println("被打断的异常2");
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    } finally {

                    }
                }
            };
            // 在未来某个时间执行给定的命令
            service.execute(run);
        }
//        do {
            try {
                System.out.println("等待1s开始");
                service.awaitTermination(1000, TimeUnit.MILLISECONDS);
                System.out.println("等待1s结束");
            } catch (InterruptedException e) {
                System.out.println("被打断的异常");
            }
//        } while (!service.isTerminated());
        System.out.println("all thread complete ");

        service.execute(() -> {
            System.out.println("shutdown后线程池不接受了，此处会报错");
        });
    }
}